package cn.fxl.pet.service.impl;

import cn.fxl.basic.exception.BusinessExciption;
import cn.fxl.basic.pageList.GmResult;
import cn.fxl.basic.result.AjaxResult;
import cn.fxl.basic.service.IBaiduAiAuditService;
import cn.fxl.basic.service.impl.BaiduAiAuditServiceImpl;
import cn.fxl.basic.utils.*;
import cn.fxl.order.domain.OrderPetAcquisition;
import cn.fxl.order.mapper.OrderPetAcquisitionMapper;
import cn.fxl.org.domain.Employee;
import cn.fxl.org.domain.Shop;
import cn.fxl.org.mapper.EmployeeMapper;
import cn.fxl.org.mapper.ShopMapper;
import cn.fxl.pet.domain.Pet;
import cn.fxl.pet.domain.SearchMasterMsg;
import cn.fxl.pet.domain.SearchMasterMsgAuditLog;
import cn.fxl.pet.mapper.PetMapper;
import cn.fxl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.fxl.pet.mapper.SearchMasterMsgMapper;
import cn.fxl.pet.query.SearchMasterMsgQuery;
import cn.fxl.pet.service.ISearchMasterMsgAuditLogService;
import cn.fxl.pet.service.ISearchMasterMsgService;
import cn.fxl.basic.service.impl.BasicServiceImpl;
import cn.fxl.user.domain.Logininfo;
import cn.fxl.user.domain.User;
import cn.fxl.user.mapper.UserMapper;
import net.bytebuddy.implementation.bind.annotation.Super;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.index.PathBasedRedisIndexDefinition;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BasicServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper ;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IBaiduAiAuditService iBaiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //先保存
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user=userMapper.getOneByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        //百度ui只能审核
        Boolean aBoolean = iBaiduAiAuditService.textAudit(searchMasterMsg.getName()+searchMasterMsg.getTitle() + searchMasterMsg.getAddress());
        Boolean aBoolean1 = iBaiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        if(aBoolean&&aBoolean1){
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");
            List<Shop> shops = shopMapper.getAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop shop = DistanceUtils.getNearestShop(point, shops);
            if(shop!=null){
                searchMasterMsg.setShopId(shop.getId());
//                SmsUtil.sendSms(shop.getTel(),"你有新宠物消息,地址在"+searchMasterMsg.getAddress());
                System.out.println("你有新宠物消息,地址在"+searchMasterMsg.getAddress());
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setState(1);
            searchMasterMsgAuditLog.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
            return AjaxResult.me();
        }else {
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("发布寻主消息失败,您的消息有非法信息");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
            return AjaxResult.me().setSuccess(false).setMsg( "发布寻主消息失败,您的消息有非法信息");
        }
    }

    @Override
    public GmResult<SearchMasterMsg> userPagequery(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.getOneByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
       return super.Pagequery(query);
    }

    @Override
    public GmResult<SearchMasterMsg> Tohandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.getByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.Pagequery(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.updateShopId(id);
    }

    /**
     * 店铺接单
     * @param map
     */
    @Override
    public void accept(Map<String, String> map) {
        long msgId = Long.parseLong(map.get("msgId"));//寻主消息id
        Long handler=Long.parseLong(map.get("handler"));//处理订单员工id
        String note = map.get("note");
        //寻主消息
        OrderPetAcquisition orderPetAcquisition=  orderPetAcquisitionMapper.getOneByMsgId(msgId);
        if(orderPetAcquisition!=null){
            throw new BusinessExciption("订单已存在,请勿重复接单");
        }
        SearchMasterMsg msgMapperOne = searchMasterMsgMapper.getOne(msgId);
      Pet pet= msgMapperOne2Pet(msgMapperOne);
        petMapper.save(pet);
        OrderPetAcquisition order=createOrder(note,pet,handler,msgMapperOne);
        orderPetAcquisitionMapper.save(order);
        rocketMQTemplate.syncSend("queue_test_topic", MessageBuilder.withPayload(order.getId()).build(),messageTimeOut,19);

        System.out.println("请到【"+msgMapperOne.getAddress()+"】接回宠物");
    }

    private OrderPetAcquisition createOrder(String note, Pet pet, Long handler, SearchMasterMsg msgMapperOne) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(pet.getUser_id()));
        orderPetAcquisition.setDigest(note);
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        orderPetAcquisition.setPrice(msgMapperOne.getPrice());
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setUserId(pet.getUser_id());
        orderPetAcquisition.setShopId(pet.getShop_id());
        orderPetAcquisition.setAddress(msgMapperOne.getAddress());
        orderPetAcquisition.setEmpId(handler);
        orderPetAcquisition.setSearchMasterMsgId(msgMapperOne.getId());
        return orderPetAcquisition;
    }

    private Pet msgMapperOne2Pet(SearchMasterMsg msgMapperOne) {
        Pet pet = new Pet();
        pet.setName(msgMapperOne.getName());
        pet.setType_id(msgMapperOne.getPetType());
        pet.setResources(msgMapperOne.getResources());
        pet.setShop_id(msgMapperOne.getShopId());
        pet.setUser_id(msgMapperOne.getUserId());
        return pet;
    }
}
